package mk.company.fin.frame.internal;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.util.List;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

import mk.company.fin.AppConstants;
import mk.company.fin.model.Organization;
import mk.company.fin.model.OrganizationSector;
import mk.company.fin.service.MessageService;
import mk.company.fin.service.ModelService;
import mk.company.fin.utils.ComboBoxElement;
import mk.company.fin.utils.ComboBoxElementRenderer;

import org.springframework.context.ApplicationContext;

public class OrganizationSectorFrame extends AbstractInternalFrame {

	private static final long serialVersionUID = -927314206394189041L;

	/* SERVICES */
	
	private MessageService messageService;
	private ModelService modelService;
	
	//component which this frame will be drawn
	JComponent component;
	public OrganizationSectorFrame(JComponent component) {
		this.component=component;
		
	}
	@Override
	public void initialize(ApplicationContext context) {
		setContext(context);
		injectServices();
		// Defaults
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(new Dimension(AppConstants.MainFrame.WIDTH, AppConstants.MainFrame.HEIGHT));
		
		// components
		initComponents();
	}
	
	/**
	 * Inject services.
	 */
	private void injectServices() {
		messageService = getContext().getBean(MessageService.class);
		modelService = getContext().getBean(ModelService.class);
	}
	@Override
	public void draw() {
		injectServices();
		initComponents();
	}
	
	public void initComponents(){
		// title
		setTitle(messageService.getMessage("organization.sector"));
		//Size
		this.setSize(AppConstants.MainFrame.WIDTH, AppConstants.MainFrame.HEIGHT);
		//Maximize
		try {
			this.setMaximum(true);
		} catch (PropertyVetoException e) {}
		catch (NullPointerException n){}
		//Layout
		this.setLayout(null);
		
		//Initialize the components of the OrganizationSectorPanel
		initOrganizationSectorPanel();
		
		//Initialize the components of the OrganizationSectorTablePanel
		initOrganizationSectorTablePanel();
		
		//Init the Action Panel
		initActionPanel();
		
		organizationSectorPanel.setVisible(false);
		this.setStyle();
		this.setVisible(true);
		component.add(this);
	}
	
	private javax.swing.JComboBox organizationNameComboBox;
    private javax.swing.JLabel organizationNameLabel;
    private javax.swing.JTextField organizationSectorCodeLField;
    private javax.swing.JLabel organizationSectorCodeLabel;
    private javax.swing.JTextField organizationSectorDescriptionField;
    private javax.swing.JLabel organizationSectorDescriptionLabel;
    private javax.swing.JPanel organizationSectorPanel;
    private Vector<ComboBoxElement<Organization>> organizationNameModel;
    private List<Organization> organizationList;
    private JButton organizationSectorActionButton;
    private javax.swing.JLabel requiredLabel;
    private javax.swing.JLabel requiredLabel1;
    private OrganizationSector selectedOrganizationSector;
    
	@SuppressWarnings("unchecked")
	private void initOrganizationSectorPanel(){
		organizationSectorPanel = new javax.swing.JPanel();
		organizationSectorPanel.setBorder(BorderFactory.createTitledBorder(messageService.getMessage("organization.sector")));
        organizationNameLabel = new javax.swing.JLabel(messageService.getMessage("organization"));
        organizationList= modelService.findAll(Organization.class);
        organizationNameModel=new Vector<ComboBoxElement<Organization>>();
        for (Organization organization:organizationList)
        	organizationNameModel.add(new ComboBoxElement<Organization>(organization, organization.getName().toString()));
        organizationNameComboBox = new javax.swing.JComboBox(organizationNameModel);
        organizationNameComboBox.setRenderer( new ComboBoxElementRenderer<Organization>());
        organizationSectorCodeLabel = new javax.swing.JLabel(messageService.getMessage("organization.sector.code"));
        organizationSectorCodeLField = new javax.swing.JTextField();
        organizationSectorCodeLField.setColumns(15);
        organizationSectorDescriptionLabel = new javax.swing.JLabel(messageService.getMessage("organization.sector.description"));
        organizationSectorDescriptionField = new javax.swing.JTextField();
        organizationSectorDescriptionField.setColumns(30);
        organizationSectorActionButton = new javax.swing.JButton();
        organizationSectorActionButton.setText(messageService.getMessage("organization.sector.save"));
        organizationSectorActionButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if (organizationSectorCodeLField.getText().equals("")){
					JOptionPane.showMessageDialog(component, messageService.getMessage("organization.sector.no.code.inputed"),"Error", JOptionPane.ERROR_MESSAGE);
				}
				else 
				if (organizationSectorDescriptionField.getText().equals("")){
					JOptionPane.showMessageDialog(component, messageService.getMessage("organization.sector.no.description.inputed"),"Error", JOptionPane.ERROR_MESSAGE);
					
				}
				else{
					try {
						if (organizationSectorActionButton.getText().equals(messageService.getMessage("organization.sector.action.add"))){
							OrganizationSector organizationSector=new OrganizationSector();
							organizationSector.setCode(organizationSectorCodeLField.getText());
							organizationSector.setDescription(organizationSectorDescriptionField.getText());
							organizationSector.setOrganization(((ComboBoxElement<Organization>)organizationNameComboBox.getSelectedItem()).getKey());
							modelService.update(organizationSector);
							clearData();
						}
						if (organizationSectorActionButton.getText().equals(messageService.getMessage("organiazation.sector.action.save"))){
							if (selectedOrganizationSector!=null){
								selectedOrganizationSector.setCode(organizationSectorCodeLField.getText());
								selectedOrganizationSector.setDescription(organizationSectorDescriptionField.getText());
								modelService.update(selectedOrganizationSector);
							}
						}
						
						organizationSectorPanel.setVisible(false);
						refreshTableData();
					}
					catch (Exception ex){
						System.out.println(ex.getMessage());
						JOptionPane.showMessageDialog(component, messageService.getMessage("organization.sector.error.writing"),"Error", JOptionPane.ERROR_MESSAGE);
						try {
							modelService.refresh(selectedOrganizationSector);
						}
						catch (Exception exc) {}
					}
				
					
				}
			}
		});
        requiredLabel = new javax.swing.JLabel();
        requiredLabel1 = new javax.swing.JLabel();
        
        requiredLabel.setForeground(new java.awt.Color(255, 0, 0));
        requiredLabel.setText("*");

        requiredLabel1.setForeground(new java.awt.Color(255, 0, 0));
        requiredLabel1.setText("*");
	}
	private javax.swing.JScrollPane organizationSectorScrollPane;
    private javax.swing.JTable organizationSectorTable;
    private javax.swing.JPanel organizationSectorTablePanel;
    private DefaultTableModel organizationSectorTableModel;
    private List<OrganizationSector> organizationSectorList;
    private javax.swing.JButton deleteOrganizationSectorButton;
    @SuppressWarnings("all")
    private void initOrganizationSectorTablePanel(){
    	organizationSectorTablePanel = new javax.swing.JPanel();
    	organizationSectorPanel.setBorder(BorderFactory.createTitledBorder(messageService.getMessage("organization.sector.list")));
        organizationSectorScrollPane = new javax.swing.JScrollPane();
        organizationSectorTable = new javax.swing.JTable();
        organizationSectorTableModel = new javax.swing.table.DefaultTableModel(
                new Object [][] {
                },
                new String [] {
                	messageService.getMessage("organization"),
                	messageService.getMessage("organization.sector.code"),
                	messageService.getMessage("organization.sector.description")
                }
            ) {
                Class[] types = new Class [] {
                    java.lang.String.class, java.lang.String.class, java.lang.String.class
                };
                boolean[] canEdit = new boolean [] {
                    false, false, false
                };

                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
                }

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            };
        organizationSectorTable.setModel(organizationSectorTableModel);
        organizationSectorTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        organizationSectorTable.setAutoCreateRowSorter(true);
        organizationSectorScrollPane.setViewportView(organizationSectorTable);
        deleteOrganizationSectorButton=new JButton();
        deleteOrganizationSectorButton.setText(messageService.getMessage("organizaton.sector.delete"));
        deleteOrganizationSectorButton.setVisible(false);
//        deleteOrganizationSectorButton.addActionListener(new ActionListener() {
//			
//			@Override
//			public void actionPerformed(ActionEvent arg0) {
//				if (organizationSectorTable.getSelectedRow()>=0){
//					OrganizationSector organizationSector=organizationSectorList.get(organizationSectorTable.getSelectedRow());
//					modelService.delete(organizationSector);
//					refreshTableData();
//				}
//			}
//		});
//        ListSelectionModel rowSelectionModel=organizationSectorTable.getSelectionModel();
//        rowSelectionModel.addListSelectionListener(new ListSelectionListener() {
//			
//			@Override
//			public void valueChanged(ListSelectionEvent e) {
//				int selectedRowIndex=organizationSectorTable.getSelectedRow();
//				if (selectedRowIndex>=0){
//					deleteOrganizationSectorButton.setVisible(true);
//				}
//				else 
//					deleteOrganizationSectorButton.setVisible(false);
//			}
//		});
        refreshTableData();
    }
    
    private javax.swing.JPanel actionPanel;
    private javax.swing.JButton addOrganizationSector;
    private javax.swing.JButton modifyOrganizationSector;
    private void initActionPanel(){
    	  actionPanel=new JPanel();
    	  actionPanel.setBorder(BorderFactory.createTitledBorder(messageService.getMessage("organization.sector.action")));
    	  addOrganizationSector=new JButton();
    	  addOrganizationSector.setText(messageService.getMessage("organization.sector.action.new"));
    	  modifyOrganizationSector=new JButton();
    	  modifyOrganizationSector.setText(messageService.getMessage("organization.sector.action.modify"));
    	  addOrganizationSector.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				organizationSectorActionButton.setText(messageService.getMessage("organization.sector.action.add"));
				organizationSectorPanel.setVisible(true);
				clearData();
			}
		});
    	  
    	 modifyOrganizationSector.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if (organizationSectorTable.getSelectedRow()>=0){
					int rowIndex=organizationSectorTable.convertRowIndexToModel(organizationSectorTable.getSelectedRow());
					selectedOrganizationSector=organizationSectorList.get(rowIndex);
					organizationSectorActionButton.setText(messageService.getMessage("organiazation.sector.action.save"));
					organizationSectorCodeLField.setText(selectedOrganizationSector.getCode());
					organizationSectorDescriptionField.setText(selectedOrganizationSector.getDescription());
					organizationSectorPanel.setVisible(true);
				}
			}
		});
          
    }
	private void setStyle(){
		 javax.swing.GroupLayout organizationSectorPanelLayout = new javax.swing.GroupLayout(organizationSectorPanel);
	        organizationSectorPanel.setLayout(organizationSectorPanelLayout);
	        organizationSectorPanelLayout.setHorizontalGroup(
	            organizationSectorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(organizationSectorPanelLayout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(organizationSectorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
	                    .addComponent(organizationNameLabel)
	                    .addComponent(organizationSectorCodeLabel)
	                    .addComponent(organizationSectorDescriptionLabel))
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                .addGroup(organizationSectorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(organizationSectorPanelLayout.createSequentialGroup()
	                        .addComponent(organizationSectorActionButton)
	                        .addGap(0, 0, Short.MAX_VALUE))
	                    .addGroup(organizationSectorPanelLayout.createSequentialGroup()
	                        .addGroup(organizationSectorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                            .addGroup(organizationSectorPanelLayout.createSequentialGroup()
	                                .addComponent(organizationSectorCodeLField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                                .addComponent(requiredLabel))
	                            .addComponent(organizationNameComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                            .addGroup(organizationSectorPanelLayout.createSequentialGroup()
	                                .addComponent(organizationSectorDescriptionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                                .addComponent(requiredLabel1)))
	                        .addContainerGap())))
	        );
	        organizationSectorPanelLayout.setVerticalGroup(
	            organizationSectorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(organizationSectorPanelLayout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(organizationSectorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(organizationNameLabel)
	                    .addComponent(organizationNameComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addGap(8, 8, 8)
	                .addGroup(organizationSectorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(organizationSectorCodeLField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                    .addComponent(organizationSectorCodeLabel)
	                    .addComponent(requiredLabel))
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addGroup(organizationSectorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(organizationSectorDescriptionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                    .addComponent(organizationSectorDescriptionLabel)
	                    .addComponent(requiredLabel1))
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(organizationSectorActionButton)
	                .addContainerGap(18, Short.MAX_VALUE))
	        );
	        javax.swing.GroupLayout organizationSectorTablePanelLayout = new javax.swing.GroupLayout(organizationSectorTablePanel);
	        organizationSectorTablePanel.setLayout(organizationSectorTablePanelLayout);
	        organizationSectorTablePanelLayout.setHorizontalGroup(
	            organizationSectorTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(organizationSectorTablePanelLayout.createSequentialGroup()
	                .addGroup(organizationSectorTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(organizationSectorTablePanelLayout.createSequentialGroup()
	                        .addContainerGap()
	                        .addComponent(organizationSectorScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 671, Short.MAX_VALUE))
	                    .addGroup(organizationSectorTablePanelLayout.createSequentialGroup()
	                        .addGap(190, 190, 190)
	                        .addComponent(deleteOrganizationSectorButton)
	                        .addGap(0, 0, Short.MAX_VALUE)))
	                .addContainerGap())
	        );
	        organizationSectorTablePanelLayout.setVerticalGroup(
	            organizationSectorTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(organizationSectorTablePanelLayout.createSequentialGroup()
	                .addGap(6, 6, 6)
	                .addComponent(organizationSectorScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                .addComponent(deleteOrganizationSectorButton)
	                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
	        );



	        javax.swing.GroupLayout actionPanelLayout = new javax.swing.GroupLayout(actionPanel);
	        actionPanel.setLayout(actionPanelLayout);
	        actionPanelLayout.setHorizontalGroup(
	            actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(actionPanelLayout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(addOrganizationSector)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                .addComponent(modifyOrganizationSector)
	                .addContainerGap(131, Short.MAX_VALUE))
	        );
	        actionPanelLayout.setVerticalGroup(
	            actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(actionPanelLayout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(addOrganizationSector)
	                    .addComponent(modifyOrganizationSector))
	                .addContainerGap(16, Short.MAX_VALUE))
	        );

	        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
	        getContentPane().setLayout(layout);
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(layout.createSequentialGroup()
	                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                            .addComponent(organizationSectorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                            .addComponent(actionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	                        .addGap(0, 0, Short.MAX_VALUE))
	                    .addComponent(organizationSectorTablePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
	                .addContainerGap())
	        );
	        layout.setVerticalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(organizationSectorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                .addComponent(actionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                .addComponent(organizationSectorTablePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addContainerGap(211, Short.MAX_VALUE))
	        );
	}
	
	@SuppressWarnings("all")
	private void refreshTableData() {
		organizationSectorList=modelService.findAll(OrganizationSector.class);
		organizationSectorTableModel.getDataVector().removeAllElements();
		organizationSectorTable.setAutoCreateRowSorter(true);
		for (OrganizationSector organizationSector:organizationSectorList){
			Vector row=new Vector();
			row.add(organizationSector.getOrganization().getName());
			row.add(organizationSector.getCode());
			row.add(organizationSector.getDescription());
			organizationSectorTableModel.addRow(row);
		}
	}
	
	private void clearData(){
		organizationSectorCodeLField.setText("");
		organizationSectorDescriptionField.setText("");
	}

}
